package com.company.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.bookstore.common.formatUtils.FormatUtils;
import com.company.bookstore.common.judgeUtils.JudgeUtils;
import com.company.bookstore.entities.book_module.Book;
import com.company.bookstore.entities.book_module.BookImg;
import com.company.bookstore.entities.book_module.Category;
import com.company.bookstore.mapper.book_module.BookCategoryMapper;
import com.company.bookstore.mapper.book_module.BookImgMapper;
import com.company.bookstore.mapper.book_module.BookMapper;
import com.company.bookstore.service.book_module.BookService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 姬深威
 * @since 2020-09-12
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    Integer FROM;
    Integer TO;

    @Resource
    private BookMapper bookMapper;

    @Resource
    BookCategoryMapper bookCategoryMapper;

    @Resource
    BookImgMapper bookImgMapper;


    /**
     * 判断from 和 to是否为空，如果其一为空则给空值赋值。如果两者都为空则不管，直接交给动态sql判断
     */
    private void isFromToNull(Integer from, Integer to) {
        if (from == null && to != null) {
            FROM = 0;
            TO = to;
        } else if (from != null && to == null) {
            FROM = from;
            TO = 99999;
        } else {
            FROM = from;
            TO = to;
        }
    }


    @Override
    public Book getBookById(Integer bookId) {
        Book book = bookMapper.getBookById(bookId);
        return FormatUtils.formatOneImgUrl(book);
    }

    public IPage<Book> getAllBooks(IPage<Book> page, Integer orderType, Integer from, Integer to) {
        isFromToNull(from, to);
        String orderType1 = JudgeUtils.judgeOrderType(orderType);
        return FormatUtils.formatManyImgUrl(bookMapper.getAllBooks(page, orderType1, FROM, TO));
    }

    public IPage<Book> getAllBooksForFront(IPage<Book> page, Integer orderType, Integer from, Integer to) {
        isFromToNull(from, to);
        String orderType1 = JudgeUtils.judgeOrderType(orderType);
        return FormatUtils.formatManyImgUrl(bookMapper.getAllBooksForFront(page, orderType1, FROM, TO));
    }

    @Override
    public IPage<Book> getBooksByCid(IPage<Book> page, Integer cId, Integer orderType, Integer from, Integer to) {
        isFromToNull(from, to);
        String orderType1 = JudgeUtils.judgeOrderType(orderType);
        return FormatUtils.formatManyImgUrl(bookMapper.getBooksByCid(page, cId, orderType1, FROM, TO));
    }

    @Override
    public IPage<Book> getBooksByCidForFront(IPage<Book> page, Integer cId, Integer orderType, Integer from, Integer to) {
        isFromToNull(from, to);
        String orderType1 = JudgeUtils.judgeOrderType(orderType);
        return FormatUtils.formatManyImgUrl(bookMapper.getBooksByCidForFront(page, cId, orderType1, FROM, TO));
    }

    @Override
    public IPage<Book> searchBooks(IPage<Book> page, Integer type, Integer orderType, String str, Integer from, Integer to) {
        isFromToNull(from, to);
        str = "%" + str + "%";
        String orderType1 = JudgeUtils.judgeOrderType(orderType);
        if (type == 1) { //根据书名模糊查询
            return FormatUtils.formatManyImgUrl(bookMapper.getBooksByName(page, str, orderType1, FROM, TO));
        } else if (type == 2) {  //根据作者模糊查询
            return FormatUtils.formatManyImgUrl(bookMapper.getBooksByAuthor(page, str, orderType1, FROM, TO));
        } else {  //根据分类模糊查询
            return FormatUtils.formatManyImgUrl(bookMapper.getBooksByCategoryName(page, str, orderType1, FROM, TO));
        }
    }

    @Override
    public IPage<Book> searchBooksForFront(IPage<Book> page, Integer type, Integer orderType, String str, Integer from, Integer to) {
        isFromToNull(from, to);
        str = "%" + str + "%";
        String orderType1 = JudgeUtils.judgeOrderType(orderType);
        if (type == 1) { //根据书名模糊查询
            return FormatUtils.formatManyImgUrl(bookMapper.getBooksByNameForFront(page, str, orderType1, FROM, TO));
        } else if (type == 2) {  //根据作者模糊查询
            return FormatUtils.formatManyImgUrl(bookMapper.getBooksByAuthorForFront(page, str, orderType1, FROM, TO));
        } else {  //根据分类模糊查询
            return FormatUtils.formatManyImgUrl(bookMapper.getBooksByCategoryNameForFront(page, str, orderType1, FROM, TO));
        }
    }


    @Override
    @Transactional(readOnly = false)
    public Integer addBooks(Book book) {
        bookMapper.addBooks(book);  //插入book到t_book
        Integer bookId = book.getId();
        List<BookImg> bookImgs = book.getBookImgs(); //从book实体类中取出BookImgs集合
        for (int i = 0; i < bookImgs.size(); i++) {
            String bookImgName = bookImgs.get(i).getImgName(); //循环把每个bookImgs的name取出来
            bookImgMapper.addImg(bookImgName, bookId);  //根据name和bookId插入book_img表
        }
        List<Category> categories = book.getCategories();  //从book实体类中取出categories集合
        for (int i = 0; i < categories.size(); i++) {
            Integer categoryId = categories.get(i).getId(); //循环把每个category的ID取出来
            bookCategoryMapper.addBookCategory(bookId, categoryId);  //根据传入的类型添加t_book_category中间表
        }
        return bookId;
    }

    @Override
    @Transactional(readOnly = false)
    public Integer deleteBook(Integer bookId) {
        //下面三个顺序必须deleteBook在最下面 因为t_book_category表和t_book_img表中有book的主键做外键 在外键表没有被删除之前t_book内容无法被删除
        bookCategoryMapper.deleteBookCategory(bookId); //删除bookId对应的所有category
        bookImgMapper.deleteImgByBookId(bookId);  //删除此书对应的Img
        Integer affectRow = bookMapper.deleteBook(bookId); //删除t_book表中的book
        return affectRow;
    }

    /**
     *
     * @param type       =1 批量删除 =2批量上架 =3批量下架
     * @param selection   选中的id数组
     * @return
     */
    @Override
    public Integer handleSelectedBooks(Integer type, Integer[] selection) {
        if (type == 1) {
            return  bookMapper.deleteSelectedBooks(selection);
        }else if (type == 2){
            return bookMapper.groundingBooks(0,selection);
        }else {
            return bookMapper.groundingBooks(1,selection);
        }
    }

    @Override
    @Transactional(readOnly = false)
    public void updateBook(Book book) {
        bookMapper.updateBook(book);
        Integer bookId = book.getId();
//        List<BookImg> bookImgs = book.getBookImgs(); //从book实体类中取出BookImgs集合
//        for (int i = 0;i<bookImgs.size();i++){
//            String bookImgName = bookImgs.get(i).getImgName(); //循环把每个bookImgs的name取出来
//            bookImgMapper.addImg(bookImgName,bookId);  //根据name和bookId插入book_img表
//        }
        List<Category> categories = book.getCategories();  //从book实体类中取出categories集合
        //删除全部该书的category
        bookCategoryMapper.deleteBookCategory(bookId);
        for (int i = 0; i < categories.size(); i++) {
            Integer categoryId = categories.get(i).getId(); //循环把每个category的ID取出来
//            if (categoryId==bookCategoryMapper.selectBookCategoryByBookId(bookId)){
//                return ;//代表需要设置的该书的category已存在
//            }
            bookCategoryMapper.addBookCategory(bookId, categoryId);  //根据传入的类型添加t_book_category中间表
        }
    }

    @Override
    public Integer handleGrounding(Book book) {
        return bookMapper.handleGrounding(book);
    }

    @Override
    public List<String> getNames() {
        return bookMapper.getNames();
    }

    @Override
    public List<Book> getNamesMapWithId(List<Integer> ids) {

      return    bookMapper.selectList(new QueryWrapper<Book>().in("id",ids));
    }
}
